package com.fh.interceptor;

import java.util.Map;

import javax.annotation.Resource;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import org.apache.commons.collections.map.HashedMap;
import org.apache.commons.lang.StringUtils;
import org.apache.log4j.Logger;
import org.apache.shiro.SecurityUtils;
import org.apache.shiro.session.Session;
import org.apache.shiro.subject.Subject;
import org.springframework.web.servlet.handler.HandlerInterceptorAdapter;

import com.fh.entity.AppUser;
import com.fh.entity.system.User;
import com.fh.service.system.appuser.AppuserService;
import com.fh.util.Const;
import com.fh.util.Constants;
import com.fh.util.Jurisdiction;
/**
 * 
* 类名称：LoginHandlerInterceptor.java
* 类描述： 
* @author FH
* 作者单位： 
* 联系方式：
* 创建时间：2015年1月1日
* @version 1.6
 */
public class LoginHandlerInterceptor extends HandlerInterceptorAdapter{
	private static final Logger logger = Logger.getLogger(LoginHandlerInterceptor.class);

	@Resource
	private AppuserService appuserService;
	
	@Override
	public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object handler) throws Exception {
		// TODO Auto-generated method stub
		String path = request.getServletPath();
		String loginKey = request.getParameter("loginKey");
		
		
		logger.info("LoginHandlerInterceptor->preHandle获取到的path ： " + path);
		if(path.matches(Const.NO_INTERCEPTOR_PATH)){
//			logger.info("不对当前Url做拦截");
			Map<String,String> map = new HashedMap();
			map.put("result", Constants.FAIL);
			map.put("errorMsg", "User is not Login");
			if(!StringUtils.isEmpty(loginKey)){
				AppUser appUser = appuserService.findByToken(loginKey);
				if(appUser != null ){
					return true;
				}else{
					logger.error("LoginKey is Valid");
					response.getWriter().println(map);
//					response.sendRedirect(WEB_BASE_URL + "/error/nouser?msg=loginKey is Inavlid&request=" + request + "&response=" + response);
					return false;
				}
			}else{
				if(path.startsWith("/happuser/login")){
					//登录接口不传loginKey可以
					return true;
				}else{
					if(!path.endsWith(".json")){
						return true;//后台的url请求不拦截
					}else{
						//不是登陆接口并且未传入loginKey直接返回错误
						response.getWriter().println(map);
						return false;
					}
				}
			}
		}else{
			//shiro管理的session
			Subject currentUser = SecurityUtils.getSubject();  
			Session session = currentUser.getSession();
			User user = (User)session.getAttribute(Const.SESSION_USER);
			if(user!=null){
				path = path.substring(1, path.length());
				boolean b = Jurisdiction.hasJurisdiction(path);
				if(!b){
					response.sendRedirect(request.getContextPath() + Const.LOGIN);
				}
				return b;
			}else{
				//登陆过滤
				response.sendRedirect(request.getContextPath() + Const.LOGIN);
				return false;		
				//return true;
			}
		}
	}
	
}
